﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Entity.Package;
using Entity.Table;
using System.Data;
using System.Configuration;
using System.IO;
using Tools;

namespace BLL.Business
{
    /// <summary>
    /// 对明细帐业务
    /// </summary>
    public class DetailAccount
    {
        public static void CheckDetailAccount(PackRequestDetailAccount detail,CSocket.ClientThread client)
        {
            try
            {
                PackReturnDetailAccount pkDuiZhangReturn = new PackReturnDetailAccount();
                pkDuiZhangReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                byte[] sendPackage = null;
                //获取明细文件，并入库
                string msg = ReadDetailFile("0009DZMX."+ detail.DzDate.Trim(),"NXS");
                //入库过程出现错误，则此对帐信息记入异常信息表,由燃气公司人员处理,退出对帐处理
                if (msg != "成功")
                {
                    TB_DetailFileException dFileException = new TB_DetailFileException("NXS",
                                                                                       detail.DzDate.Trim(),
                                                                                       Convert.ToDecimal(detail.PayMoneyHJ.Trim()),
                                                                                       0,
                                                                                       "NXS"+detail.DzDate+".txt",
                                                                                       msg);

                    Db.DetailFileExceptionManager.Insert(dFileException); //入库失败，存入异常信息
                    if (msg == "对帐文件不存在")
                    {
                        PackFailReturn pkFailReturn = new PackFailReturn();
                        pkFailReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                        pkFailReturn.ResponseCode = ((int)ResponseCode.文件不存在).ToString().PadLeft(3, '0');
                        pkFailReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                        byte[] sendFailPackage = CSocket.PackageHandle.CombinationPackage(pkFailReturn);
                        if (client.Send(sendFailPackage))  //发送返回包
                            client.CloseSocket();  //断开链接
                    }
                    return;
                }

                //核对总帐金额与明细总金额是否相符
                decimal detailTotalMoney = Db.CheckAccountDetailTempManager.GetDetailAccountTotalMoney("NXS",detail.DzDate.Trim());
              
               
                if (detailTotalMoney != Convert.ToDecimal(detail.PayMoneyHJ))
                {
                    TB_DetailFileException dFileException = new TB_DetailFileException("NXS",detail.DzDate.Trim(),
                                                                                        Convert.ToDecimal(detail.PayMoneyHJ.Trim()),
                                                                                        detailTotalMoney,
                                                                                        "NXS" + detail.DzDate.Trim() + ".txt",
                                                                                       "总对帐金额与明细对帐总额不符，明细文件有错，请与银行核实");

                    Db.DetailFileExceptionManager.Insert(dFileException); //金额不符，存入异常信息

                    LogHelper.WriteInfoLog(string.Format("明细帐总金额与总帐金额不符；明细帐总金额：{0},总帐金额：{1} ",
                                            detailTotalMoney, detail.PayMoneyHJ.Trim()));

                    pkDuiZhangReturn.ResponseCode = ((int)ResponseCode.总账不平).ToString().PadLeft(3, '0');
                    pkDuiZhangReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkDuiZhangReturn.ToString()).Length).ToString());
                    sendPackage = CSocket.PackageHandle.CombinationPackage(pkDuiZhangReturn);
                    if (client.Send(sendPackage))  //发送返回包
                        client.CloseSocket();  //断开链接
                    return;
                }

                // 给银行发送成功返回包
              
                pkDuiZhangReturn.StrokeCount = detail.StrokeCount.Trim();
                pkDuiZhangReturn.PayMoneyHJ = detail.PayMoneyHJ.Trim();
                pkDuiZhangReturn.ResponseCode = ((int)ResponseCode.交易成功).ToString().PadLeft(3, '0');
                pkDuiZhangReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkDuiZhangReturn.ToString()).Length).ToString());
                sendPackage = CSocket.PackageHandle.CombinationPackage(pkDuiZhangReturn);
                if (client.Send(sendPackage))  //发送返回包
                    client.CloseSocket();  //断开链接

                //核对明细帐
                string startDate = "";
                string endDate = "";
                string businessDate = detail.DzDate.Trim();
               
                startDate = businessDate+"000000";
                endDate = businessDate+ "235959";

                if (!Db.ReconcileManager.PerformReconcile(startDate,endDate,"NXS"))
                {
                    LogHelper.WriteInfoLog(string.Format("核对明细帐失败: 起始时间：{0}，截止时间：{1},业务日期:{2}",
                                            startDate.Trim(), endDate.Trim(),detail.DzDate.Trim()));
                  
                    TB_DetailFileException dFileException = new TB_DetailFileException("NXS",detail.DzDate.Trim(),
                                                                                          Convert.ToDecimal(detail.PayMoneyHJ.Trim()),
                                                                                          detailTotalMoney,
                                                                                          "NXS"+detail.DzDate.Trim()+".txt",
                                                                                          " 对帐时，数据库出现异常，需手工核查");
                    
                    Db.DetailFileExceptionManager.Insert(dFileException); //入库失败，存入异常信息
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("CheckDetailAccount方法-核对明细帐出现异常，异常信息：" + ex.Message, ex);
                PackFailReturn pkFailReturn = new PackFailReturn();
                pkFailReturn.TradeCode = ((int)TradeCode.对明细帐).ToString();
                pkFailReturn.ResponseCode = ((int)ResponseCode.其他错误).ToString().PadLeft(3,'0');
                pkFailReturn.PackHead = new PackHead(detail.packHead.PayWay, detail.packHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                CSocket.PackageHandle.SendFailurPackage(pkFailReturn,client);
                
            }
        }


        /// <summary>
        /// 明细对帐文件信息入库
        /// </summary>
        /// <param name="filename"></param>
        private static string ReadDetailFile(string filename,string bankCode)
        {
            string errMsg="";
            string path = ConfigurationManager.AppSettings["FilePath"].ToString();
            path = System.IO.Path.Combine(path, filename);
           
            if (File.Exists(path))
            {
                try
                {
                    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string message = sr.ReadToEnd();

                    //清空明细对帐临时表
                    Db.CheckAccountDetailTempManager.Delete(bankCode);

                    string[] items = message.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string str in items)
                    {
                        string[] temp = str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        TB_CheckAccountDetailTemp detail = new TB_CheckAccountDetailTemp("NXS",temp[0], temp[1], temp[2], temp[3]);

                        //入库
                        if (!Db.CheckAccountDetailTempManager.Insert(detail))
                        {
                            LogHelper.WriteInfoLog("明细对帐信息入库失败");
                            errMsg = "明细对帐信息入库失败";
                            break;
                        }
                    }
                }
                catch
                {
                    errMsg = "文件读取失败";
                    LogHelper.WriteErrorLog("ReadDetailFile方法-文件读取失败");
                }
                errMsg = "成功";
            }
            else
            {
                errMsg = "对帐文件不存在";
                LogHelper.WriteInfoLog("对帐文件不存在" + path);
            }

            return errMsg;
        }
    }
}
